import json

# 数据模型类
class Book:
    def __init__(self, book_id, title, author, isbn, publication_year, status='Available'):
        self.book_id = book_id
        self.title = title
        self.author = author
        self.isbn = isbn
        self.publication_year = publication_year
        self.status = status

class Reader:
    def __init__(self, reader_id, name, contact_info, registration_date):
        self.reader_id = reader_id
        self.name = name
        self.contact_info = contact_info
        self.registration_date = registration_date

class Borrow:
    def __init__(self, borrow_id, book_id, reader_id, borrow_date, return_date=None):
        self.borrow_id = borrow_id
        self.book_id = book_id
        self.reader_id = reader_id
        self.borrow_date = borrow_date
        self.return_date = return_date

# 数据管理类
class LibraryDataManager:
    def __init__(self, filepath):
        self.filepath = filepath
        self.data = self.load_data()

    def load_data(self):
        try:
            with open(self.filepath, 'r', encoding='utf-8') as file:
                self.data = json.load(file)
                return self.data
        except (FileNotFoundError, json.JSONDecodeError):
            return {"books": [], "readers": [], "borrows": []}

    def save_data(self):
        try:
            with open(self.filepath, 'w', encoding='utf-8') as file:
                json.dump(self.data, file, indent=4)
        except IOError as e:
            print(f"无法写入文件：{e}")

# 功能模块（图书管理、读者管理、借阅管理等）
class BookManager:
    def __init__(self, data_manager):
        self.data_manager = data_manager
        self.books = self.data_manager.data["books"]

    def add_book(self, title, author, isbn, publication_year):
        l = len(self.books)
        book_id = str(1) if l == 0 else str(int(self.books[l - 1]["BookID"]) + 1)
        
        new_book = {
            "BookID": book_id,
            "Title": title,
            "Author": author,
            "ISBN": isbn,
            "Publication Year": publication_year,
            "Status": "Available"
        }
        self.books.append(new_book)
        self.data_manager.save_data()

    def remove_book(self, book_id):
        self.books = [book for book in self.books if book["BookID"] != book_id]
        self.data_manager.save_data()

    def update_book(self, book_id, **kwargs):
        for book in self.books:
            if book["BookID"] == book_id:
                for key, value in kwargs.items():
                    if key in book:
                        book[key] = value
        self.data_manager.save_data()

    def find_books(self, **search_criteria):
        results = self.books
        for key, value in search_criteria.items():
            results = [book for book in results if book.get(key) == value]
        return results

    def report_damaged(self, book_id):
        for book in self.books:
            if book["BookID"] == book_id:
                book["Status"] = "Damaged"
        self.data_manager.save_data()

class ReaderManager:
    def __init__(self, data_manager):
        self.data_manager = data_manager
        self.readers = self.data_manager.data["readers"]

    def add_reader(self, name, contact_info, registration_date):
        l = len(self.readers)
        reader_id = str(1) if l == 0 else str(int(self.readers[l - 1]["ReaderID"]) + 1)

        new_reader = {
            "ReaderID": reader_id,
            "Name": name,
            "Contact Information": contact_info,
            "Registration Date": registration_date
        }
        self.readers.append(new_reader)
        self.data_manager.save_data()

    def remove_reader(self, reader_id):
        self.readers = [reader for reader in self.readers if reader["ReaderID"] != reader_id]
        self.data_manager.save_data()

    def update_reader(self, reader_id, **kwargs):
        for reader in self.readers:
            if reader["ReaderID"] == reader_id:
                for key, value in kwargs.items():
                    if key in reader:
                        reader[key] = value
        self.data_manager.save_data()

    def find_readers(self, **search_criteria):
        results = self.readers
        for key, value in search_criteria.items():
            results = [reader for reader in results if reader.get(key) == value]
        return results

class BorrowManager:
    def __init__(self, data_manager, book_manager, reader_manager):
        self.data_manager = data_manager
        self.book_manager = book_manager
        self.reader_manager = reader_manager
        self.borrows = self.data_manager.data["borrows"]

    def borrow_book(self, book_id, reader_id, borrow_date):
        book = next((book for book in self.book_manager.books if book["BookID"] == book_id), None)
        if book and book["Status"] == "Available":
            book["Status"] = "Borrowed"

            l = len(self.borrows)
            borrow_id = str(1) if l == 0 else str(int(self.borrows[l - 1]["BorrowID"]) + 1)
            new_borrow = {
                "BorrowID": borrow_id,
                "BookID": book_id,
                "ReaderID": reader_id,
                "Borrow Date": borrow_date,
                "Return Date": None
            }
            self.borrows.append(new_borrow)
            self.book_manager.update_book(book_id, Status="Borrowed")
            self.data_manager.save_data()
            print("图书借阅成功。")
        else:
            print("图书不可借阅。")

    def return_book(self, book_id):
        borrow = next((borrow for borrow in self.borrows if borrow["BookID"] == book_id and borrow["Return Date"] is None), None)
        if borrow:
            borrow["Return Date"] = input("请输入还书日期：")
            self.book_manager.update_book(book_id, Status="Available")
            self.data_manager.save_data()
            print("图书归还成功。")
        else:
            print("找不到借阅记录。")

# 用户界面
def book_management_menu(book_manager):
    while True:
        print("\n图书管理")
        print("1. 添加图书")
        print("2. 删除图书")
        print("3. 修改图书信息")
        print("4. 查询图书")
        print("5. 报告图书损坏")
        print("6. 返回主菜单")
        choice = input("请选择一个操作：")
        if choice == '1':
            title = input("请输入书名：")
            author = input("请输入作者：")
            isbn = input("请输入ISBN：")
            publication_year = input("请输入出版年份：")
            book_manager.add_book(title, author, isbn, publication_year)
            print("图书添加成功。")
        elif choice == '2':
            book_id = input("请输入要删除的图书ID：")
            book_manager.remove_book(book_id)
            print("图书删除成功。")
        elif choice == '3':
            book_id = input("请输入要修改的图书ID：")
            print("请输入新的图书信息（留空则不修改）：")
            title = input("书名：")
            author = input("作者：")
            isbn = input("ISBN：")
            publication_year = input("出版年份：")
            status = input("状态：")
            updates = {k: v for k, v in [('Title', title), ('Author', author), ('ISBN', isbn), ('Publication Year', publication_year), ('Status', status)] if v}
            book_manager.update_book(book_id, **updates)
            print("图书信息更新成功。")
        elif choice == '4':
            search_criteria = {}
            print("请输入查询条件（留空则跳过该条件）：")
            search_criteria['Title'] = input("书名：")
            search_criteria['Author'] = input("作者：")
            search_criteria['ISBN'] = input("ISBN：")
            search_criteria = {k: v for k, v in search_criteria.items() if v}
            results = book_manager.find_books(**search_criteria)
            print("查询结果：")
            for book in results:
                print(book)
        elif choice == '5':
            book_id = input("请输入要报告损坏的图书ID：")
            book_manager.report_damaged(book_id)
            print("图书报损成功。")
        elif choice == '6':
            break
        else:
            print("无效的选择，请重新选择。")

def reader_management_menu(reader_manager):
    while True:
        print("\n读者管理")
        print("1. 添加读者")
        print("2. 删除读者")
        print("3. 修改读者信息")
        print("4. 查询读者")
        print("5. 返回主菜单")
        choice = input("请选择一个操作：")
        if choice == '1':
            name = input("请输入读者姓名：")
            contact_info = input("请输入读者联系方式：")
            registration_date = input("请输入注册日期：")
            reader_manager.add_reader(name, contact_info, registration_date)
            print("读者添加成功。")
        elif choice == '2':
            reader_id = input("请输入要删除的读者ID：")
            reader_manager.remove_reader(reader_id)
            print("读者删除成功。")
        elif choice == '3':
            reader_id = input("请输入要修改的读者ID：")
            print("请输入新的读者信息（留空则不修改）：")
            name = input("姓名：")
            contact_info = input("联系方式：")
            registration_date = input("注册日期：")
            updates = {k: v for k, v in [('Name', name), ('Contact Information', contact_info), ('Registration Date', registration_date)] if v}
            reader_manager.update_reader(reader_id, **updates)
            print("读者信息更新成功。")
        elif choice == '4':
            search_criteria = {}
            print("请输入查询条件（留空则跳过该条件）：")
            search_criteria['Name'] = input("姓名：")
            search_criteria['ReaderID'] = input("读者ID：")
            search_criteria = {k: v for k, v in search_criteria.items() if v}
            results = reader_manager.find_readers(**search_criteria)
            print("查询结果：")
            for reader in results:
                print(reader)
        elif choice == '5':
            break
        else:
            print("无效的选择，请重新选择。")

def borrow_management_menu(borrow_manager):
    while True:
        print("\n借阅管理")
        print("1. 借书")
        print("2. 还书")
        print("3. 返回主菜单")
        choice = input("请选择一个操作：")
        if choice == '1':
            book_id = input("请输入图书ID：")
            reader_id = input("请输入读者ID：")
            borrow_date = input("请输入借书日期：")
            borrow_manager.borrow_book(book_id, reader_id, borrow_date)
        elif choice == '2':
            book_id = input("请输入图书ID：")
            borrow_manager.return_book(book_id)
        elif choice == '3':
            break
        else:
            print("无效的选择，请重新选择。")

def main_menu():
    # 准备数据
    data_manager = LibraryDataManager("library.json")
    book_manager = BookManager(data_manager)
    reader_manager = ReaderManager(data_manager)
    borrow_manager = BorrowManager(data_manager, book_manager, reader_manager)
    while True:
        print("\n图书馆管理系统")
        print("1. 图书管理")
        print("2. 读者管理")
        print("3. 借阅管理")
        print("4. 退出")
        choice = input("请选择一个操作：")
        if choice == '1':
            book_management_menu(book_manager)
        elif choice == '2':
            reader_management_menu(reader_manager)
        elif choice == '3':
            borrow_management_menu(borrow_manager)
        elif choice == '4':
            print("感谢使用！")
            break
        else:
            print("无效的选择，请重新选择。")

if __name__ == '__main__':
    main_menu()
